package com.zjsru.leetcode75.level1;

/**
 * @Author: cookLee
 * @Date: 2023-10-03
 * 反转字符串中的元音字母
 */
public class ReverseVowels {
    /**
     * 主
     * 输入：s = "hello"
     * 输出："holle"
     * \
     * 输入：s = "leetcode"
     * 输出："leotcede"
     *
     * @param args args
     */
    public static void main(String[] args) {
        ReverseVowels reverseVowels = new ReverseVowels();
        String s = "hello";
        System.out.println(reverseVowels.reverseVowels(s));
    }

    /**
     * 哈希:标记所有ASCII字符是否是元音
     */
    static boolean[] hash = new boolean[128];

    static char[] vowels = new char[]{'a', 'e', 'i', 'o', 'u'};

    static char CHARACTER_EMPTY = ' ';

    /**
     * 做一次映射：将对应的元音转化到哈希表上
     */
    static {
        for (char c : vowels) {
            hash[c - CHARACTER_EMPTY] = hash[Character.toUpperCase(c) - CHARACTER_EMPTY] = true;
        }
    }

    /**
     * 反转元音:双指针，两百年都指向元音时反转
     *
     * @param s s
     * @return {@link String}
     */
    public String reverseVowels(String s) {
        char[] words = s.toCharArray();
        int left = 0;
        int right = words.length - 1;
        while (left < right) {
            //获取对应的字母的哈希值
            if (hash[words[left] - CHARACTER_EMPTY] && hash[words[right] - CHARACTER_EMPTY]) {
                this.helper(words, left++, right--);
            } else {
                if (!hash[words[left] - CHARACTER_EMPTY]) {
                    left++;
                }
                if (!hash[words[right] - CHARACTER_EMPTY]) {
                    right--;
                }
            }
        }
        return String.valueOf(words);
    }

    /**
     * 交换元音字符串
     *
     * @param words 字词
     * @param l     l
     * @param r     右
     */
    private void helper(char[] words, int l, int r) {
        char c = words[l];
        words[l] = words[r];
        words[r] = c;
    }
}
